/*
 *  @Title SecurePropertyPlaceholderConfigurer.java
 *  @Package： com.phoenix.core.spring
 *  Copyright (c) 2017 by 江苏深南互联网金融信息服务有限公司  All right reserved
 */
package com.phoenix.core.spring;

import java.util.Enumeration;
import java.util.Properties;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.core.io.Resource;
import org.springframework.util.ObjectUtils;

import com.phoenix.core.logger.SimpleLogger;
import com.phoenix.core.util.JcSecureUtil;

/**
 *  @ClassName SecurePropertyPlaceholderConfigurer
 *  @Description 属性文件解密加载
 *  @author liuwei
 *  @version 1.0
 *  @date 2017年4月20日
 */
public class SecurePropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {

	private SimpleLogger logger = SimpleLogger.getLogger(this.getClass());

	@Override
	protected String convertProperty(String propertyName, String propertyValue) {
		String decodeStr = null;
		if (StringUtils.isNotBlank(propertyValue)) {
			decodeStr = JcSecureUtil.decodeCard(propertyValue);
			if (decodeStr != null) {
				propertyValue = decodeStr;
			}
		}
		if (logger.isDebugEnabled())
			logger.debug("load property:" + propertyName + "=" + propertyValue);
		return super.convertProperty(propertyName, propertyValue);
	}

	protected void convertProperties(Properties props) {
		Enumeration<?> propertyNames = props.propertyNames();
		while (propertyNames.hasMoreElements()) {
			String propertyName = (String) propertyNames.nextElement();
			String propertyValue = props.getProperty(propertyName);
			String convertedValue = convertProperty(propertyName, propertyValue);
			if (!ObjectUtils.nullSafeEquals(propertyValue, convertedValue)) {
				props.setProperty(propertyName, convertedValue);
				if (logger.isDebugEnabled())
					logger.debug("set property:" + propertyName + "=" + convertedValue);
			}
		}
	}

	protected Resource[] locations;

	@Override
	public void setLocations(Resource... locations) {
		super.setLocations(locations);
		this.locations = locations;
	}

	@Override
	public void setLocation(Resource location) {
		super.setLocation(location);
		this.locations = new Resource[] { location };
	}

}
